package org.share.develop.selfloader;

import org.share.develop.api.Order;
import org.share.develop.proxy.javassist.JavassistCompiler;

public class ApiClassLoader extends ClassLoader{

    static  String  cls = "package org.share.develop.api;\n" +
            "\n" +
            "import java.io.Serializable;\n" +
            "\n" +
            "public class Order implements Serializable {\n" +
            "\n" +
            "    private Long id;\n" +
            "    private String name;\n" +
            "    private String location;\n" +
            "\n" +
            "\n" +
            "    public Long getId() {\n" +
            "        return id;\n" +
            "    }\n" +
            "\n" +
            "    public void setId(Long id) {\n" +
            "        this.id = id;\n" +
            "    }\n" +
            "\n" +
            "    public String getName() {\n" +
            "        return name;\n" +
            "    }\n" +
            "\n" +
            "    public void setName(String name) {\n" +
            "        this.name = name;\n" +
            "    }\n" +
            "\n" +
            "    public String getLocation() {\n" +
            "        return location;\n" +
            "    }\n" +
            "\n" +
            "    public void setLocation(String location) {\n" +
            "        this.location = location;\n" +
            "    }\n" +
            "\n" +
            "    public static Order getInstance(){\n" +
            "        return  new Order();\n" +
            "    }\n" +
            "\n" +
            "    public String toString(){\n" +
            "        System.err.println(2);\n" +
            "        return \"123\";\n" +
            "    }\n" +
            "}\n" +
            "\n";




    public ApiClassLoader(ClassLoader parent) {
        super(parent);
    }

    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class clazz = null;
        JavassistCompiler javassistCompiler = new JavassistCompiler();


        try {
            clazz = javassistCompiler.doCompile("org.share.develop.api.Order",cls);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        if (clazz == null) {
            throw new ClassNotFoundException(name);
        }
        return clazz;
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Order order = new Order();
        System.err.println(order.toString());
        ApiClassLoader apiClassLoader = new ApiClassLoader(Thread.currentThread().getContextClassLoader());

        order = (Order) apiClassLoader.findClass("Order").newInstance();
        order.toString();

    }

}
